package app.android.kdictionary.Activity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import app.android.kdictionary.R;
import app.android.kdictionary.R.id;
import app.android.kdictionary.Util.HttpParser;
import app.android.kdictionary.Util.HttpRequester;
import app.android.kdictionary.Util.HttpURLMgr;
import app.android.kdictionary.adapter.WebAdapter;
import app.android.kdictionary.aidl.SearchResultData;
import app.android.kdictionary.aidl.WebViewContent;
import app.android.kdictionary.enums.SearchResultType;
import app.android.kdictionary.enums.SearchType;

public class SearchResultActivity extends Activity {
	private ListView listView;
	
	private WebAdapter mAdapter;
	
	private SharedPreferences sharedPreferences;
	private SharedPreferences.Editor sharedEditor;
	
	private BackGroundThread backGroundThread;
	
	private String jamo;

	private String startText;
	private String endText;
	
	private String[] searchText;
	private String[] table;
	private String[] gubun;
	private String[] orgLang;
	private String[] techTerm;
	private String[] spCode;
	
	private String[] jaso;
	
	private int size=0;
	private HttpURLMgr hum;
	private HttpRequester hr;
	private HttpParser hp;
	
	private SearchType searchType;
	
	private String metaString = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_result);
        
		findView();
		init();
    }
    
    private void findView() {
    	listView = (ListView)findViewById(id.search_result_list);
    }
    
    private void init() {
		hum = new HttpURLMgr();
		hr = new HttpRequester();
		hp = new HttpParser();
    	
    	sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    	sharedEditor = sharedPreferences.edit();

//Toast.makeText(getBaseContext(), "click item : "+sharedPreferences.getString("searchWord", ""), Toast.LENGTH_SHORT).show();

    	Intent intent = getIntent();
    	searchType = SearchType.valueOf(intent.getStringExtra("searchType"));
    	switch(searchType) {
	    	case INDEX_SEARCH :
	    		jamo = intent.getStringExtra("jamo"); 
	    		break;
	    		
	    	case JASO_SEARCH :
	    		jaso = intent.getStringArrayExtra("jaso");
	    		break;
	    		
	    	case MULTI_SEARCH :
	        	searchText = intent.getStringArrayExtra("searchText");
	        	table = intent.getStringArrayExtra("table");
	        	gubun = intent.getStringArrayExtra("gubun");
	        	orgLang = intent.getStringArrayExtra("orgLang");
	        	techTerm = intent.getStringArrayExtra("techTerm");
	    		spCode = intent.getStringArrayExtra("spCode");
	    		break;
	    		
	    	case RANGE_SEARCH :
	    		startText = intent.getStringExtra("startText");
	    		endText = intent.getStringExtra("endText");
	    		break;
    	}
		
        mAdapter = new WebAdapter(getLayoutInflater());
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(mItemClickListener);
        
    	if( backGroundThread == null ) {
    		backGroundThread = (BackGroundThread) new BackGroundThread();
    		backGroundThread.execute(false);
    	}
    	else {
    		switch(backGroundThread.getStatus()) {
        		case PENDING :
        		case RUNNING :
        			backGroundThread.cancel(true);
        		case FINISHED :
        			backGroundThread = (BackGroundThread) new BackGroundThread();
        			backGroundThread.execute(false);
        			break;
    		}	
    	}
    }
    
	private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
			switch( mAdapter.getItem(position).getType() ) {
				case ADD :
					mAdapter.removeLastItem();
					
		        	if( backGroundThread == null ) {
		        		backGroundThread = (BackGroundThread) new BackGroundThread();
		        		backGroundThread.execute(true);
		        	}
		        	else {
		        		switch(backGroundThread.getStatus()) {
			        		case PENDING :
			        		case RUNNING :
			        			backGroundThread.cancel(true);
			        		case FINISHED :
			        			backGroundThread = (BackGroundThread) new BackGroundThread();
			        			backGroundThread.execute(true);
			        			break;
		        		}	
		        	}
					break;
					
				case RESULT :
					sharedEditor.putInt("idx", mAdapter.getItem(position).getIdx());
					sharedEditor.commit();
	
					Intent startIntent  = new Intent(getBaseContext(), ResultActivity.class);
					startActivity(startIntent);	
					break;
					
				case NOTFOUND :
					break;
					
				case PROGRESS :
					break;
			}
		}
	};
	
	// AsyncTask클래스는 항상 Subclassing 해서 사용 해야 함.
    // 사용 자료형은
    // background 작업에 사용할 data의 자료형: String 형
    // background 작업 진행 표시를 위해 사용할 인자: Integer형
    // background 작업의 결과를 표현할 자료형: Long
	private class BackGroundThread extends AsyncTask<Boolean, Integer, Integer> {
		private SearchResultData searchResultData;
		
    	// 이곳에 포함된 code는 AsyncTask가 execute 되자 마자 UI 스레드에서 실행됨.
    	// 작업 시작을 UI에 표현하거나
    	// background 작업을 위한 ProgressBar를 보여 주는 등의 코드를 작성.
		@Override
		protected void onPreExecute() {
			mAdapter.addItem(new WebViewContent(-1, "", SearchResultType.PROGRESS) );
			
//			for(int i=0; i<searchText.length; i++) {
//				Log.i("searchText "+i+">", "<"+searchText[i]+">");
//				Log.i("table "+i+">", "<"+table[i]+">");
//				Log.i("gubun "+i+">", "<"+gubun[i]+">");
//				Log.i("orgLang "+i+">", "<"+orgLang[i]+">");
//				Log.i("techTerm "+i+">", "<"+techTerm[i]+">");
//			}
//			for(int i=0; i<spCode.length; i++) {
//				Log.i("spCode"+i+">", spCode[i]);
//			}
			
			super.onPreExecute();
		}

		// UI 스레드에서 AsynchTask객체.execute(...) 명령으로 실행되는 callback 
		@Override
    	protected Integer doInBackground(Boolean... isNextSearch) {
    		
        	ArrayList<WebViewContent> list = new ArrayList<WebViewContent>();
        	
        	try {
        		switch(searchType) {
	        		case INDEX_SEARCH :
	        			if(isNextSearch[0]) {
	                		hum.setNextPage();
	                		hp.parseSectionList(hr.request(hum.getUrl(), "POST", hum.getParams()), list);
	        			}
	        			else {
	                		hum.setJamoSearchParams(jamo);
	                		size = Integer.parseInt(hp.getSimpleAmount(hr.request(hum.getUrl(), "POST", hum.getParams())));
	                		hp.parseSectionList(hr.request(hum.getUrl(), "POST", hum.getParams()), list);
	        			}
	        			break;
	        			
	        		case JASO_SEARCH :
	        			if(isNextSearch[0]) {
	                		hum.setNextPage();
	                		hp.parseSectionList(hr.request(hum.getUrl(), "POST", hum.getParams()), list);
	        			}
	        			else {
		            		hum.setJasoSearchParams(jaso);
		            		size = Integer.parseInt(hp.getSimpleAmount(hr.request(hum.getUrl(), "POST", hum.getParams())));
		            		hp.parseSectionList(hr.request(hum.getUrl(), "POST", hum.getParams()), list);
	        			}
	        			break;
	        			
	        			
	        		case MULTI_SEARCH :
	        			if(isNextSearch[0]) {
	            			try {
	                    		hum.setNextPage();
	                    		hp.parseSectionList(hr.request(hum.getUrl(), "POST", hum.getParams()), list);
	                    	} catch (Exception e) {
	                    		e.printStackTrace();
	                    	}
	            		}
	            		else {
	            			try {
	                    		hum.setMultiSearchParams(searchText, table, gubun, orgLang, techTerm, spCode);
	                    		size = Integer.parseInt(hp.getSimpleAmount(hr.request(hum.getUrl(), "POST", hum.getParams())));
	                    		hp.parseSectionList(hr.request(hum.getUrl(), "POST", hum.getParams()), list);
	                    	} catch (Exception e) {
	                    		e.printStackTrace();
	                    	}
	            		}
	        			break;
	        			
	        			
	        		case RANGE_SEARCH :
	        			if(isNextSearch[0]) {
	                		hum.setNextPage();
	                		hp.parseSectionList(hr.request(hum.getUrl(), "POST", hum.getParams()), list);
	        			}
	        			else {
	                		hum.setRangeSearchParams(startText, endText);
	                		size = Integer.parseInt(hp.getSimpleAmount(hr.request(hum.getUrl(), "POST", hum.getParams())));
	                		hp.parseSectionList(hr.request(hum.getUrl(), "POST", hum.getParams()), list);
	        			}
	        			break;
        		}

        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        	
        	searchResultData = new SearchResultData();
        	searchResultData.setWebViewSize(size);
        	searchResultData.setWebViewContentList(list);
			
    		return 1;
    	}
    	
    	// onInBackground(...)에서 publishProgress(...)를 사용하면
    	// 자동 호출되는 callback으로 이곳에서 ProgressBar를 증가 시키고, 
		// text 정보를 update하는 등의 background 작업 진행 상황을 UI에 표현함.
    	@Override
    	protected void onProgressUpdate(Integer... progress) {
    	}
    	
    	// onInBackground(...)가 완료되면 자동으로 실행되는 callback
    	@Override
    	protected void onPostExecute(Integer result) {
    		mAdapter.removeLastItem();
    		
    		ArrayList<WebViewContent> list = searchResultData.getWebViewContentList();    		
    		int size = searchResultData.getWebViewSize();
    		
    		if(size==0) {
    			mAdapter.addItem(new WebViewContent(-1, metaString+getString(R.string.not_found_string), SearchResultType.NOTFOUND));
    		}
    		else {
    			// mAdapter addItems
        		mAdapter.addItems(list);
            	
            	if( mAdapter.getCount()<size ) {
        			mAdapter.addItem(new WebViewContent(-1, metaString+getString(R.string.more_string), SearchResultType.ADD));
            	}
    		}
    		
        	Log.i("SearchResultActivity", "SIZE :" + size + "\nlist size :"+list.size()+"\nmAdapter size:"+mAdapter.getCount());
    	}
    	
    	// AsyncTask.cancel(boolean) 메소드가 true 인자로 
    	// 실행되면 호출되는 콜백.
    	// background 작업이 취소될때 꼭 해야될 작업은  여기에 구현.
    	@Override
		protected void onCancelled() {
			super.onCancelled();
		}  
	}
}